package com.gogowan.agroenterprise;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.Toast;

//import java.util.List;
//import com.gogowan.agriculture.model.MaterialBatch;
import com.gogowan.agroenterprise.barcode.Intents;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.CodeActivationInfo;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.MaterialBatch;
import com.gogowan.agroenterprise.model.MaterialBatchResultInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.NewCodeValidationRequest;
import com.gogowan.agroenterprise.model.NewCodeValidationResult;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.SalesPlaceDict;
import com.gogowan.agroenterprise.model.SellMaterialInfo;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * @author Mainac
 * @功能描述 记录销售信息 并上传 步骤：先拍首尾码 得到批次列表以及每个批次所对应的产品名称， 用户只需填写销售信息。
 * @since 2013.10.29 添加拍新格式码
 */
public class SalesActivity extends BaseActivity {

	private static int START = 1; // 调用拍码requestCode
	private static int END = 2;

	private Button takeStart; // 起始 拍码按钮
	private Button takeEnd; // 截止 拍码按钮
	private EditText startText; // 起始 I-OID显示
	private EditText endText; // 截止 I-OID显示
	private EditText salesEnterprises;// 销售单位
	private EditText salesPerson;// 销售人员
	private Button save;
	private Button back;
	private int codeType = -1;
	/**
	 * 批次
	 */
//	private EditText batch;
	/**
	 * 二级批次
	 */
//	private EditText batchSec;
	/**
	 * 选择批次
	 */
//	private Spinner batchSpinner;
	/**
	 * 选择二级批次
	 */
//	private Spinner batchSpinnerSec;
//	private TableRow secTR;

	private Spinner isPublicOrSec;
	private boolean isPublic = true;

	/**
	 * 销售渠道
	 */
	private Spinner channel;
	/**
	 * 销售产品名称
	 */
	private EditText productName;

	private ProgressDialog progressDialog;
	private SharedPreferences preferences;
	private MaterialBatchResultInfo resultInfo;
	// private String selectedProductName;
	private long selectedChannel;
//	private long selectedBatch;
//	private long selectedBatchSec;
	private long selectedMaterialId;
	private long enterpriseId;
	private long personId;
	private String personName;
//	private String enterpriseName;
	private String startCode;
	private String endCode;

//	private List<MaterialBatch> batches;
//	private List<MaterialBatch> batchesSec;
	private boolean isNew;
	private Button datePicker;
	private String date = "";

	private boolean isNewCode = false;
	private String startCodStr;
	private String endCodStr;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sales);

		takeStart = (Button) findViewById(R.id.sales_btn_paima_start);
		takeEnd = (Button) findViewById(R.id.sales_btn_paima_end);
		startText = (EditText) findViewById(R.id.sales_start_ed);
		endText = (EditText) findViewById(R.id.sales_end_ed);
		salesEnterprises = (EditText) findViewById(R.id.sales_enterprises);
		salesPerson = (EditText) findViewById(R.id.sales_person);

		save = (Button) findViewById(R.id.sales_save_btn);
		back = (Button) findViewById(R.id.sales_backBtn);

//		batch = (EditText) findViewById(R.id.sales_batch);
//		batchSec = (EditText) findViewById(R.id.sales_batch_sec);
//		batchSpinner = (Spinner) findViewById(R.id.sales_batchesSpinner);
//		batchSpinnerSec = (Spinner) findViewById(R.id.sales_batchesSpinner_sec);
//		secTR = (TableRow) findViewById(R.id.sales_secTR);
//		isPublicOrSec = (Spinner) findViewById(R.id.sales_status);
		channel = (Spinner) findViewById(R.id.sales_channel);
		productName = (EditText) findViewById(R.id.sales_product_name);
		datePicker = (Button) findViewById(R.id.sales_dateBtn);
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		personId = preferences.getLong("personid", 0);
		isNew = preferences.getBoolean("isNew", false);

//		salesPlaceDict = loginResultInfo.getSalesplacedict();
		personName = MyApplication.mSettings.getString("username","");
//		enterpriseName = loginResultInfo.getEnterpriseinfo().getEname();

		salesEnterprises.setText("enterpriseName");
		salesPerson.setText(personName);
		String[] m1;
//		if (salesPlaceDict == null || salesPlaceDict.length == 0) {
//			// showFinishDialog("初始化销售经销商失败！");
//			// 提示无销售经销商
//			m1 = new String[1];
//			m1[0] = "无销售经销商";
//			channel.setEnabled(false);
//		} else {
//			m1 = new String[salesPlaceDict.length];
//			for (int i = 0; i < salesPlaceDict.length; i++) {
//				m1[i] = salesPlaceDict[i].getSalesplacename();
//			}
//			channel.setEnabled(true);
//		}
//		ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
//				SalesActivity.this, R.layout.simple_spinner_item, m1);
//		// 设置下拉列表的风格
//		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//		// 将adapter 添加到spinner中
//		channel.setAdapter(adapter1);


		takeStart.setOnClickListener(startPaima);
		takeEnd.setOnClickListener(endPaima);
		save.setOnClickListener(saveCallback);
		back.setOnClickListener(backToIndex);
		datePicker.setOnClickListener(dateBtnCallback);

		channel.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				channel.setSelection(position);
//				if (salesPlaceDict.length == 0) {
//					selectedChannel = 0;
//				} else {
//					selectedChannel = salesPlaceDict[position]
//							.getSalesplaceid();
//				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// do nothing
			}
		});

		// 设置公共、子批次的显示风格
		/*ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(
				SalesActivity.this, R.layout.simple_spinner_item, new String[] {
						"公共", "子批次" });
		// 设置下拉列表的风格
		adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		isPublicOrSec.setAdapter(adapter1);
		// 公共、子批次
		isPublicOrSec.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				if (arg2 == 0) {
					isPublic = true;
					secTR.setVisibility(View.GONE);
				} else if (arg2 == 1) {
					isPublic = false;
					secTR.setVisibility(View.VISIBLE);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
			}
		});

		batchSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				List<MaterialBatch> batchestest = batches;
				MaterialBatch mb = batches.get(position);
				selectedBatch = batches.get(position).getBatchid();
				productName
						.setText(batches.get(position).getMaterialfullname());
				
				 * if (selectedBatch == -1) { secTR.setVisibility(View.GONE);
				 * return; } else { secTR.setVisibility(View.VISIBLE); }
				 

				batchesSec = batches.get(position).getBactchList();
				List<MaterialBatch> batchesSectest = batchesSec;

				if (batchesSec != null && batchesSec.size() > 0) {

					isPublicOrSec.setSelection(0);
					isPublicOrSec.setEnabled(true);
					isPublicOrSec.setFocusable(true);

					batchSec.setVisibility(View.GONE);
					batchSpinnerSec.setVisibility(View.VISIBLE);

					String[] m = new String[batchesSec.size()];
					for (int i = 0; i < batchesSec.size(); i++) {
						m[i] = batchesSec.get(i).getBatchcode();
					}
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(
							SalesActivity.this, R.layout.simple_spinner_item, m);
					// 设置下拉列表的风格
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					// 将adapter 添加到spinner中
					batchSpinnerSec.setAdapter(adapter);

					batchSpinnerSec
							.setOnItemSelectedListener(new OnItemSelectedListener() {

								@Override
								public void onItemSelected(AdapterView<?> arg0,
										View arg1, int arg2, long arg3) {
									selectedBatchSec = batchesSec.get(arg2)
											.getBatchid();
								}

								@Override
								public void onNothingSelected(
										AdapterView<?> arg0) {
									selectedBatchSec = batchesSec.get(0)
											.getBatchid();
								}
							});
				} else {
					isPublicOrSec.setSelection(0);
					isPublic = true;
					isPublicOrSec.setEnabled(false);
					isPublicOrSec.setFocusable(false);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// donothing
				selectedBatch = batches.get(0).getBatchid();
			}
		});*/
	}

	/**
	 * 时间选择按钮点击事件
	 */
	public Button.OnClickListener dateBtnCallback = new Button.OnClickListener() {

		@SuppressWarnings("deprecation")
		@Override
		public void onClick(View v) {
			showDialog(0);
		}
	};

	/**
	 * 创建日期及时间选择对话框
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog = null;
		switch (id) {
		case 0:
			Calendar c = Calendar.getInstance();
			dialog = new DatePickerDialog(this,
					new DatePickerDialog.OnDateSetListener() {
						@SuppressWarnings("deprecation")
						public void onDateSet(DatePicker dp, int year,
								int month, int dayOfMonth) {

							SimpleDateFormat df = new SimpleDateFormat(
									"yyyy-MM-dd");// 设置日期格式
							String nowDate = df.format(new Date());
							String cDate = year + "-" + (month + 1) + "-"
									+ dayOfMonth;

							java.util.Calendar c1 = java.util.Calendar
									.getInstance();
							java.util.Calendar c2 = java.util.Calendar
									.getInstance();
							try {
								c1.setTime(df.parse(nowDate));
								c2.setTime(df.parse(cDate));
							} catch (java.text.ParseException e) {
								System.err.println("格式不正确");
							}
							int result = c1.compareTo(c2);

							if (result >= 0) {
								datePicker.setText(year + "-" + (month + 1)
										+ "-" + dayOfMonth);
								date = year + "-" + (month + 1) + "-"
										+ dayOfMonth;
							} else {
								Toast.makeText(SalesActivity.this,
										getString(R.string.date_error),
										Toast.LENGTH_LONG).show();
							}
						}
					}, c.get(Calendar.YEAR), // 传入年份
					c.get(Calendar.MONTH), // 传入月份
					c.get(Calendar.DAY_OF_MONTH) // 传入天数
			);
			break;
		}
		return dialog;

	}

	private void showFinishDialog(String string) {
		new AlertDialog.Builder(SalesActivity.this).setTitle("警告")
				.setMessage(string).setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// SalesActivity.this.finish();
					}
				}).create().show();
	}

	/*
	 * 拍起始码按钮事件
	 */
	public Button.OnClickListener startPaima = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(SalesActivity.this,
					PaiMaTypeMoreActivity.class);
			intent.putExtra("type", 1);
			startActivityForResult(intent, 10);
		}
	};
	/*
	 * 拍截止码按钮事件
	 */
	public Button.OnClickListener endPaima = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(SalesActivity.this,
					PaiMaTypeMoreActivity.class);
			startActivityForResult(intent, 20);
		}
	};

	/**
	 * 保存按钮事件
	 */
	public Button.OnClickListener saveCallback = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			try {
				SellMaterialInfo sellMaterialInfo = new SellMaterialInfo();

				if (startCode != null) {
					sellMaterialInfo.setStartcode(startCode);
				} else {
					Toast.makeText(SalesActivity.this, "起始码内容为空",
							Toast.LENGTH_LONG).show();
					return;
				}

				if (!TextUtils.isEmpty(endCode)) {
					sellMaterialInfo.setEndcode(endCode);
					sellMaterialInfo.setType(codeType);
				} else {
					Toast.makeText(SalesActivity.this, "截止码内容为空",
							Toast.LENGTH_LONG).show();
					return;
				}

				/*if (isNewCode) {
					if (selectedBatch != 0) {
						sellMaterialInfo.setBatchid(selectedBatch);
					} else {
						Toast.makeText(SalesActivity.this, "批次ID为空",
								Toast.LENGTH_LONG).show();
						return;
					}
					if (isPublic) {
						sellMaterialInfo.setBatchidSec(-1);
					} else {
						if (selectedBatchSec != 0) {
							sellMaterialInfo.setBatchidSec(selectedBatchSec);
						} else {
							Toast.makeText(SalesActivity.this, "子批次ID为空",
									Toast.LENGTH_LONG).show();
							return;
						}
					}
				}*/
				if (selectedChannel == 0) {
					showFinishDialog("销售经销商不能为空");
					return;
				}
				sellMaterialInfo.setMaterialid(selectedMaterialId);
				sellMaterialInfo.setEnterpriseid(enterpriseId);
				sellMaterialInfo.setPersonid(personId);
				sellMaterialInfo.setSalesplaceid(selectedChannel);
				sellMaterialInfo.setIsnew(isNew);
				if (date.equals("")) {
					Toast.makeText(SalesActivity.this, "请设置生产日期",
							Toast.LENGTH_LONG).show();
					return;
				}
				sellMaterialInfo.setProductionTime(date);

				progressDialog = ProgressDialog.show(SalesActivity.this, "提示",
						"正在保存....", true, false);
				SaveAsyn saveAsyn = new SaveAsyn();
				saveAsyn.execute(sellMaterialInfo);
			} catch (Exception e) {
				new AlertDialog.Builder(SalesActivity.this)
						.setTitle("警告")
						.setMessage("数据保存有误！")
						.setCancelable(false)
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										startText.setText("");
										endText.setText("");
										startCode = null;
										endCode = null;
									}
								}).create().show();
			}
		}

	};
	/*
	 * 返回主页按钮事件
	 */
	public Button.OnClickListener backToIndex = new Button.OnClickListener() {

		@Override
		public void onClick(View v) {
			SalesActivity.this.finish();
			// AlertDialog alert = new AlertDialog.Builder(SalesActivity.this)
			// .setTitle(getString(R.string.tip_back))
			// .setCancelable(false)
			// .setMessage(getString(R.string.tip_back_description))
			// .setNegativeButton("否", new AlertDialog.OnClickListener() {
			// public void onClick(DialogInterface dialog,
			// int whichButton) {
			// // do nothing
			// }
			// })
			// .setPositiveButton("是", new AlertDialog.OnClickListener() {
			// public void onClick(DialogInterface dialog,
			// int whichButton) {
			// SalesActivity.this.finish();
			// }
			// }).create();
			// alert.show();
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			AlertDialog alert = new AlertDialog.Builder(SalesActivity.this)
					.setTitle(getString(R.string.tip_back))
					.setCancelable(false)
					.setMessage(getString(R.string.tip_back_description))
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							SalesActivity.this.finish();
						}
					}).create();
			alert.show();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 拍码返回处理
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 10) {
			if (resultCode == 1) {
				Intent intent = new Intent(Intents.Scan.ACTION);
				intent.putExtra("type", 1);
				startActivityForResult(intent, START);
			} else if (resultCode == 2) {
				LayoutInflater inflater = LayoutInflater
						.from(SalesActivity.this);
				View view = inflater.inflate(R.layout.dialog_edit, null);
				final EditText text = (EditText) view
						.findViewById(R.id.dialog_edittext);
				text.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start,
							int before, int count) {
						// 判断是否有中文如果有中文替换为""
						String str = text.getText().toString().trim();
						String regEx = "[\u4e00-\u9fa5]";
						Pattern p = Pattern.compile(regEx);
						Matcher m = p.matcher(str);
						if (m.find()) {

							text.setText(m.replaceAll("").trim());

						}

					}

					@Override
					public void beforeTextChanged(CharSequence s, int start,
							int count, int after) {
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable s) {
						// TODO Auto-generated method stub
						String str = text.getText().toString().trim();
						text.setSelection(str.length());
					}
				});
				AlertDialog.Builder builder1 = new AlertDialog.Builder(
						SalesActivity.this);
				builder1.setTitle("请输入您要拍的码号");
				builder1.setView(view);
				builder1.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								String contents = text.getText().toString()
										.trim();
								if (TextUtils.isEmpty(contents)) {
									Toast.makeText(SalesActivity.this,
											"起始码内容不能为空", Toast.LENGTH_LONG)
											.show();
								} else {
									startText.setText(contents);
									startCode = contents;
									takeEnd.setEnabled(true);
									takeEnd.setFocusable(true);
								}

							}
						});
				builder1.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});
				builder1.create().show();
			}
		} else if (requestCode == 20) {
			if (resultCode == 1) {
				Intent intent = new Intent(Intents.Scan.ACTION);
				intent.putExtra("type", 1);
				startActivityForResult(intent, END);
			} else if (resultCode == 2) {
				LayoutInflater inflater = LayoutInflater
						.from(SalesActivity.this);
				View view = inflater.inflate(R.layout.dialog_edit, null);
				final EditText text = (EditText) view
						.findViewById(R.id.dialog_edittext);
				text.addTextChangedListener(new TextWatcher() {

					@Override
					public void onTextChanged(CharSequence s, int start,
							int before, int count) {
						// 判断是否有中文如果有中文替换为""
						String str = text.getText().toString().trim();
						String regEx = "[\u4e00-\u9fa5]";
						Pattern p = Pattern.compile(regEx);
						Matcher m = p.matcher(str);
						if (m.find()) {

							text.setText(m.replaceAll("").trim());

						}

					}

					@Override
					public void beforeTextChanged(CharSequence s, int start,
							int count, int after) {
						// TODO Auto-generated method stub

					}

					@Override
					public void afterTextChanged(Editable s) {
						// TODO Auto-generated method stub
						String str = text.getText().toString().trim();
						text.setSelection(str.length());
					}
				});
				AlertDialog.Builder builder1 = new AlertDialog.Builder(
						SalesActivity.this);
				builder1.setTitle("请输入您要拍的码号");
				builder1.setView(view);
				builder1.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								String contents = text.getText().toString()
										.trim();
								if (TextUtils.isEmpty(contents)) {
									Toast.makeText(SalesActivity.this,
											"截止码内容不能为空", Toast.LENGTH_LONG)
											.show();
								} else {
									endText.setText(contents);
									endCode = contents;
									isNewCode = true;
									NewCodeValidationRequest request = new NewCodeValidationRequest();
									request.setBeginEWM(startCode);
									request.setEndEWM(endCode);
									request.setEnterpriseId(enterpriseId);

									progressDialog = ProgressDialog.show(
											SalesActivity.this, "提示",
											"正在查询....", true, false);

									NewCodeAsyn asyn = new NewCodeAsyn();
									asyn.execute(request);
								}
							}
						});
				builder1.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

							}
						});
				builder1.create().show();
			}
		} else if (resultCode == RESULT_OK) {

			if (requestCode == START) {

				String contents = data.getStringExtra("SCAN_RESULT").trim();
				String code = Utils.getCodeStr(contents);
				// String [] ss = contents.split("ewm=");
				// String code = ss[ss.length-1];

				// startCodStr = Utils.getIDcodeStr(code);
				// if (startCodStr == "") {
				// Toast.makeText(SalesActivity.this, "码内容不符合I-OID规则",
				// Toast.LENGTH_LONG).show();
				// } else {
				// if (Utils.isNumeric(code)) {
				// startText.setText(code);
				// takeEnd.setEnabled(true);
				// takeEnd.setFocusable(true);
				//
				// CodeActivationInfo requestBatchsInfo = new
				// CodeActivationInfo();
				// requestBatchsInfo.setStartcode(contents);
				// requestBatchsInfo.setEnterpriseid(enterpriseId);
				//
				// FirstGetAsyn firstGetAsyn = new FirstGetAsyn();
				// firstGetAsyn.execute(requestBatchsInfo);
				//
				// } else {
				startText.setText(code);
				startCode = contents;
				takeEnd.setEnabled(true);
				takeEnd.setFocusable(true);
				// }
				// }

			} else if (requestCode == END) {

				String contents = data.getStringExtra("SCAN_RESULT").trim();
				// String [] ss = contents.split("=");
				// String code = ss[ss.length-1];
				String code = Utils.getCodeStr(contents);

				// endCodStr = Utils.getIDcodeStr(code);
				// if (endCodStr == "") {
				// Toast.makeText(SalesActivity.this, "码内容不符合I-OID规则",
				// Toast.LENGTH_LONG).show();
				// } else {
				//
				// if (endCodStr.trim().length() == startCodStr.trim()
				// .length()) {
				//
				// if (Long.valueOf(endCodStr) < Long.valueOf(startCodStr)) {
				// Toast.makeText(SalesActivity.this, "截止码应大于或等于起始码",
				// Toast.LENGTH_LONG).show();
				// } else {
				//
				// if (Utils.isNumeric(code)) {
				// endText.setText(code);
				//
				// progressDialog = ProgressDialog.show(
				// SalesActivity.this, "提示", "正在查询....",
				// true, false);
				//
				// CodeActivationInfo requestBatchsInfo = new
				// CodeActivationInfo();
				// requestBatchsInfo.setStartcode(startCode);
				// requestBatchsInfo.setEndcode(contents);
				// requestBatchsInfo.setEnterpriseid(enterpriseId);
				//
				// RequestBatchsAsyn requestBatchsAsyn = new
				// RequestBatchsAsyn();
				// requestBatchsAsyn.execute(requestBatchsInfo);
				//
				// } else {
				// 如果当前首码不是新码则弹出提示
				endText.setText(code);
				endCode = contents;
				isNewCode = true;
				NewCodeValidationRequest request = new NewCodeValidationRequest();
				request.setBeginEWM(startCode);
				request.setEndEWM(endCode);
				request.setEnterpriseId(enterpriseId);

				progressDialog = ProgressDialog.show(SalesActivity.this, "提示",
						"正在查询....", true, false);

				NewCodeAsyn asyn = new NewCodeAsyn();
				asyn.execute(request);
				// }

				// }
				//
				// } else {
				// Toast.makeText(SalesActivity.this, "截止码与起始码位数不同",
				// Toast.LENGTH_LONG).show();
				// }
				// }

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 判断数组内是不是均为数字
	 * 
	 * @param content
	 * @return true 是
	 */
	private boolean isAllNumeric(String content) {
		String[] ss = content.split("\\.");
		if (ss.length == 0 || !ss[0].equals("i")) {
			return false;
		}
		for (int i = 1; i < ss.length; i++) {
			if (!Utils.isNumeric(ss[i])) {
				return false;
			}
		}
		return true;
	}

	/**
	 * @author Maniac
	 * @描述 根据首尾I-OID码请求批次列表] (改) 判断首尾码是不是在同一个批次
	 */
	private class RequestBatchsAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SalesActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					endText.setText("");
					endCode = null;
					Toast.makeText(SalesActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string,
							ResultInfo.class);
					int i = resultInfo.getResult();
					if (i == 4010) {
						endCode = endText.getText().toString().trim();
						Toast.makeText(SalesActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					} else {
						Toast.makeText(SalesActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
						endText.setText("");
						// 不清空起始码
						endCode = null;
					}
				}
			}

			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(4000, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}

	/**
	 * @author Administrator
	 * @功能 保存信息
	 */
	private class SaveAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SalesActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(SalesActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo) Utils.fromJSON(string,
							ResultInfo.class);
					if (resultInfo.getResult() == 4110) {
						Toast.makeText(SalesActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
						SalesActivity.this.finish();
					} else {
						startText.setText("");
						endText.setText("");
						productName.setText("");
//						batch.setText("");
						startCode = null;
						endCode = null;
						Toast.makeText(SalesActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			SellMaterialInfo sellMaterialInfo = (SellMaterialInfo) params[0];
			String json = Utils.toJSON(sellMaterialInfo);
			Message message = new Message(4100, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	/**
	 * 根据起始码请求当前码所在的产品批次号和产品名称
	 */
	private class FirstGetAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SalesActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {

				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(SalesActivity.this,
							getString(R.string.analyse_error),
							Toast.LENGTH_LONG).show();
				} else {
					resultInfo = (MaterialBatchResultInfo) Utils.fromJSON(
							string, MaterialBatchResultInfo.class);

					if (resultInfo.getResult() == 4210) {

						startCode = startText.getText().toString().trim();

						String productNameString = resultInfo.getMbatcharray()[0]
								.getMaterialfullname();
						if (productNameString != null
								&& !productNameString.equals("")) {
							productName.setText(productNameString);
						} else {
							startCode = null;
							startText.setText("");
							return;
						}

						String batchSecString = resultInfo.getExtBatchName();
						if (batchSecString != null) {
//							batchSec.setText(batchSecString);
						}

						String batchNameString = resultInfo.getMbatcharray()[0]
								.getBatchcode();
						if (batchNameString != null
								&& !batchNameString.equals("")) {
//							batch.setText(batchNameString);
						} else {
							startCode = null;
							startText.setText("");
							return;
						}

						takeEnd.setEnabled(true);
					} else {
						takeEnd.setEnabled(false);
						startCode = null;
						startText.setText("");
						Toast.makeText(SalesActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
					}
				}
			}
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			CodeActivationInfo request = (CodeActivationInfo) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(4200, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	/**
	 * 新码的请求批次
	 * 
	 * @author Administrator
	 */
	private class NewCodeAsyn extends MyAsyncTask {

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(SalesActivity.this,
						getString(R.string.server_error), Toast.LENGTH_LONG)
						.show();
			} else {
				Message message = (Message) Utils.fromJSON((String) res,
						Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(SalesActivity.this,
							getString(R.string.server_error), Toast.LENGTH_LONG)
							.show();
				} else {
					NewCodeValidationResult resultInfo = (NewCodeValidationResult) Utils
							.fromJSON(string, NewCodeValidationResult.class);
					int result = resultInfo.getResult();
					if (result == 12010) {

//						save.setEnabled(true);
						if (resultInfo.getMaterialFullName() != null) {
							productName.setText(resultInfo
									.getMaterialFullName());
						}
						selectedMaterialId = resultInfo.getMaterialId();
						codeType = resultInfo.getType();
						/*batches = resultInfo.getBatch();
						List<MaterialBatch> batchestest = batches;
						if (batches != null && batches.size() > 0) {
							batch.setVisibility(View.GONE);
							batchSpinner.setVisibility(View.VISIBLE);

							batchSec.setVisibility(View.GONE);
							batchSpinnerSec.setVisibility(View.VISIBLE);

							int length = batches.size(); // 将返回的数据中的商品名称拿出来
							String[] materials = new String[length]; // 组成一个新数组
							for (int i = 0; i < length; i++) { //
								materials[i] = batches.get(i).getBatchcode(); //
							}
							// String[] newMaterial = toDiffArray(materials); //
							// 数组去重
							ArrayAdapter<String> adapter = new ArrayAdapter<String>(
									SalesActivity.this,
									R.layout.simple_spinner_item, materials);
							// 设置下拉列表的风格
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							// 将adapter 添加到spinner中
							batchSpinner.setAdapter(adapter);
						}*/
					} else {
						Toast.makeText(SalesActivity.this,
								resultInfo.getResultinfo(), Toast.LENGTH_LONG)
								.show();
						endText.setText("");
//						save.setEnabled(false);
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			NewCodeValidationRequest request = (NewCodeValidationRequest) params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(12000, true, json);
			String ss = Utils.toJSON(message);
			Log.i("gggggggggggggggggg===", ss);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}

	}

	/**
	 * 数组去重
	 * 
	 * @param
	 * @return
	 */
	public static String[] toDiffArray(String[] s) {
		Set<String> set = new HashSet<String>();
		for (String sa : s) {
			set.add(sa);
		}
		return set.toArray(new String[] {});
	}
}
